'use client';
import { useState, useEffect, useCallback } from 'react';
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Search, PlusCircle, Clock, Trash2, Edit3, AlertCircle } from "lucide-react";
import { Spinner } from '@/components/ui/Spinner';
import { useToast } from '@/hooks/use-toast';
import Link from 'next/link';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Skeleton } from "@/components/ui/skeleton";

// Custom debounce function
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

const TemplateCardSkeleton = () => {
  return (
    <Card className="group relative p-5 hover:shadow-md transition-all bg-card border border-border/40">
      <div className="space-y-4">
        <div className="flex justify-between items-start">
          <div className="space-y-2">
            <Skeleton className="h-6 w-[180px]" />
            <Skeleton className="h-4 w-[240px]" />
          </div>
          <Skeleton className="h-8 w-24 rounded-lg" />
        </div>

        <div className="flex items-center gap-2">
          <Skeleton className="h-4 w-4" />
          <Skeleton className="h-4 w-32" />
        </div>
      </div>
    </Card>
  );
};

const TemplateListSkeleton = () => {
  return (
    <div className="mt-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
      <Card className="group relative border p-5 hover:shadow-md transition-all bg-card cursor-pointer border-dashed h-[180px] flex items-center justify-center">
        <div className="flex flex-col items-center gap-2">
          <Skeleton className="h-10 w-10 rounded-full" />
          <Skeleton className="h-5 w-24" />
        </div>
      </Card>
      {[...Array(5)].map((_, index) => (
        <TemplateCardSkeleton key={index} />
      ))}
    </div>
  );
};

// 在文件顶部添加API基础URL配置
// 使用Next.js API路由来处理请求，避免跨域问题
// const API_BASE_URL = 'http://localhost:3001'; // 移除这个硬编码的URL

async function getTemplates() {
  const res = await fetch('/api/templates', {  // 使用API路由路径
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  if (!res.ok) {
    throw new Error('获取模板失败');
  }
  return res.json();
}

async function createTemplate(templateData) {
  const res = await fetch('/api/templates', {  // 使用API路由路径
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(templateData),
  });
  if (!res.ok) {
    throw new Error('创建模板失败');
  }
  return res.json();
}

// 确保updateTemplate函数也使用API路由路径
async function updateTemplate(id, templateData) {
  const res = await fetch(`/api/templates/${id}`, {  // 使用API路由路径
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(templateData),
  });
  if (!res.ok) {
    throw new Error('更新模板失败');
  }
  return res.json();
}

// 确保deleteTemplate函数也使用API路由路径
async function deleteTemplate(id) {
  const res = await fetch(`/api/templates/${id}`, {  // 使用API路由路径
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  if (!res.ok) {
    throw new Error('删除模板失败');
  }
  return res.json();
}

// New Template Card
const NewTemplateCard = ({ onClick }) => {
  return (
    <Card 
      onClick={onClick}
      className="group relative border p-5 hover:shadow-xl transition-all duration-300 ease-in-out bg-card cursor-pointer border-dashed h-[180px] flex items-center justify-center overflow-hidden"
    >
      <div className="flex flex-col items-center gap-3 text-muted-foreground group-hover:scale-110 transition-transform duration-300">
        <div className="bg-primary/10 p-3 rounded-full">
          <PlusCircle className="h-8 w-8 text-primary" />
        </div>
        <span className="text-sm font-medium">新建模板</span>
      </div>
      <div className="absolute inset-0 bg-gradient-to-br from-primary/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
    </Card>
  );
};

// Template Card Component
const TemplateCard = ({ template, onEdit, onDelete }) => {
  return (
    <Card className="group relative p-5 hover:shadow-md transition-all bg-card border border-border/40">
      <div className="space-y-4">
        <div className="flex justify-between items-start">
          <div className="space-y-2">
            <h3 className="text-lg font-semibold tracking-tight group-hover:text-primary transition-colors">{template.name}</h3>
            <p className="text-sm text-muted-foreground line-clamp-2">{template.content}</p>
          </div>
          <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
            <Button
              size="sm"
              variant="ghost"
              className="h-8 w-8 p-0 rounded-full"
              onClick={() => onEdit(template)}
            >
              <Edit3 className="h-4 w-4" />
              <span className="sr-only">编辑模板</span>
            </Button>
            <Button
              size="sm"
              variant="ghost"
              className="h-8 w-8 p-0 rounded-full text-destructive hover:text-destructive hover:bg-destructive/10"
              onClick={() => onDelete(template)}
            >
              <Trash2 className="h-4 w-4" />
              <span className="sr-only">删除按钮</span>
            </Button>
          </div>
        </div>

        <div className="flex items-center gap-2 text-xs text-muted-foreground">
          <Clock className="h-3.5 w-3.5" />
          <span>{new Date(template.created_at).toLocaleDateString()}</span>
        </div>
        
        {template.var && (
          <div className="flex items-start gap-2">
            <Badge variant="secondary" className="bg-primary/10 text-primary hover:bg-primary/20">变量: {template.var}</Badge>
          </div>
        )}
      </div>
    </Card>
  );
};

export default function TemplatePage() {
  const { toast } = useToast();
  const [templates, setTemplates] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [templateToDelete, setTemplateToDelete] = useState(null);
  const [showNewTemplateDialog, setShowNewTemplateDialog] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState(null);
  const [newTemplate, setNewTemplate] = useState({
    name: '',
    content: '',
    var: '',
  });

  const debouncedSearch = useCallback((value) => {
    const timeoutId = setTimeout(() => {
      setSearchQuery(value);
    }, 300);
    return () => clearTimeout(timeoutId);
  }, []);

  // Fetch templates
  useEffect(() => {
    const fetchTemplates = async () => {
      try {
        setIsLoading(true);
        const data = await getTemplates();
        setTemplates(data.map(template => ({
          ...template,
          created_at: template.created_at || new Date().toISOString()
        })));
      } catch (error) {
        console.error('获取模板错误:', error);
        toast({
          title: '错误',
          description: error.message,
          variant: 'destructive'
        });
      } finally {
        setIsLoading(false);
      }
    };

    fetchTemplates();
  }, [toast]);

  // Filter templates
  const filteredTemplates = templates.filter(template => {
    return template.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
           template.content.toLowerCase().includes(searchQuery.toLowerCase()) ||
           template.var.toLowerCase().includes(searchQuery.toLowerCase());
  });

  // Handle create/update template
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      setIsSubmitting(true);
      
      if (editingTemplate) {
        // Update existing template
        await updateTemplate(editingTemplate.id, newTemplate);
        toast({
          title: '更新成功',
          variant: 'default'
        });
      } else {
        // Create new template
        await createTemplate(newTemplate);
        toast({
          title: '创建成功',
          variant: 'default'
        });
      }
      
      // Reset form and close dialog
      resetForm();
      setShowNewTemplateDialog(false);
      
      // Refresh templates list
      await getTemplates().then(data => {
        setTemplates(data.map(template => ({
          ...template,
          created_at: template.created_at || new Date().toISOString()
        })));
      });
    } catch (error) {
      console.error('保存模板错误:', error);
      toast({
        title: '错误',
        description: error.message,
        variant: 'destructive'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  // Handle delete template
  const handleDelete = async () => {
    try {
      await deleteTemplate(templateToDelete.id);
      toast({
        title: '删除成功',
        variant: 'default'
      });
      
      // Remove from local state
      setTemplates(templates.filter(t => t.id !== templateToDelete.id));
    } catch (error) {
      console.error('删除模板错误:', error);
      toast({
        title: '错误',
        description: error.message,
        variant: 'destructive'
      });
    } finally {
      setDeleteDialogOpen(false);
      setTemplateToDelete(null);
    }
  };

  // Open edit dialog
  const handleEdit = (template) => {
    setEditingTemplate(template);
    setNewTemplate({
      name: template.name,
      content: template.content,
      var: template.var,
    });
    setShowNewTemplateDialog(true);
  };

  // Open delete confirmation dialog
  const handleDeleteClick = (template) => {
    setTemplateToDelete(template);
    setDeleteDialogOpen(true);
  };

  // Reset form
  const resetForm = () => {
    setEditingTemplate(null);
    setNewTemplate({
      name: '',
      content: '',
      var: '',
    });
  };

  // Open create dialog
  const handleNewTemplate = () => {
    resetForm();
    setShowNewTemplateDialog(true);
  };

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">模板管理</h1>
          <p className="text-gray-600">创建和管理您的提示词模板</p>
        </div>
        
        <div className="relative w-full md:w-64">
          <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            type="text"
            placeholder="搜索模板..."
            className="pl-8"
            onChange={(e) => {
              const cleanup = debouncedSearch(e.target.value);
              return () => cleanup();
            }}
          />
        </div>
      </div>

      {isLoading ? (
        <TemplateListSkeleton />
      ) : (
        <div className="mt-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
          <NewTemplateCard onClick={handleNewTemplate} />
          {filteredTemplates.length === 0 ? (
            <div className="col-span-full flex flex-col items-center justify-center py-12 text-center">
              <AlertCircle className="h-12 w-12 text-muted-foreground mb-4" />
              <h3 className="text-lg font-medium mb-2">未找到模板</h3>
              <p className="text-sm text-muted-foreground max-w-md">
                {searchQuery ? 
                  "没有模板匹配您的搜索条件。请尝试使用其他搜索词。" :
                  "您还没有任何模板。点击'新建模板'卡片来创建一个。"
                }
              </p>
            </div>
          ) : (
            filteredTemplates.map(template => (
              <TemplateCard
                key={template.id}
                template={template}
                onEdit={handleEdit}
                onDelete={handleDeleteClick}
              />
            ))
          )}
        </div>
      )}

      {/* New/Edit Template Dialog */}
      <Dialog open={showNewTemplateDialog} onOpenChange={setShowNewTemplateDialog}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>{editingTemplate ? "编辑模板" : "新建模板"}</DialogTitle>
            <DialogDescription>
              {editingTemplate ? 
                "修改下方的模板详情。" :
                "为您的提示词创建一个新模板。"
              }
            </DialogDescription>
          </DialogHeader>
          
          <form onSubmit={handleSubmit} className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="name">名称</Label>
              <Input
                id="name"
                value={newTemplate.name}
                onChange={(e) => setNewTemplate({...newTemplate, name: e.target.value})}
                placeholder="输入模板名称"
                required
              />
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="content">内容</Label>
              <Textarea
                id="content"
                value={newTemplate.content}
                onChange={(e) => setNewTemplate({...newTemplate, content: e.target.value})}
                placeholder="输入模板内容"
                className="min-h-[150px]"
                required
              />
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="var">变量</Label>
              <Input
                id="var"
                value={newTemplate.var}
                onChange={(e) => setNewTemplate({...newTemplate, var: e.target.value})}
                placeholder="输入模板变量（逗号分隔）"
              />
            </div>
            
            <DialogFooter className="sm:justify-between">
              <Button variant="ghost" onClick={() => {
                resetForm();
                setShowNewTemplateDialog(false);
              }}>
                取消
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? (
                  <>
                    <Spinner className="mr-2 h-4 w-4" />
                    保存中...
                  </>
                ) : (
                  editingTemplate ? "更新" : "创建"
                )}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>删除</DialogTitle>
            <DialogDescription>
              您确定要删除这个模板吗？此操作无法撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={handleDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}